package com.example.lemis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.lemis.common.exception.IllegalArgException;
import com.example.lemis.common.exception.NotLoginException;
import com.example.lemis.common.utils.SessionUtils;
import com.example.lemis.model.domain.Admin;
import com.example.lemis.model.domain.Doorplate;
import com.example.lemis.mapper.DoorplateMapper;
import com.example.lemis.model.dto.DoorplateInsertDTO;
import com.example.lemis.model.dto.DoorplateQuery;
import com.example.lemis.model.dto.DoorplateSummaryQuery;
import com.example.lemis.model.dto.PageDTO;
import com.example.lemis.model.vo.AdminInfoVO;
import com.example.lemis.model.vo.DoorplateSummaryVO;
import com.example.lemis.model.vo.DoorplateVO;
import com.example.lemis.model.vo.userDoorplateVO;
import com.example.lemis.service.BaseCurdService;
import com.example.lemis.service.IAdminService;
import com.example.lemis.service.IDoorplateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 管理门牌数据 服务实现类
 * </p>
 *
 * @author lxp
 * @since 2025-06-24
 */
@Service
@AllArgsConstructor
public class DoorplateServiceImpl extends ServiceImpl<DoorplateMapper, Doorplate> implements IDoorplateService,
        BaseCurdService<Doorplate> {
    private final DoorplateMapper doorplateMapper;
    private final IAdminService adminService;

    @Override
    public Page<userDoorplateVO> doorplate_search_admin(PageDTO pageDTO, String name) {
        Page<userDoorplateVO> page = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());
        page = doorplateMapper.doorplate_search_admin(page, name);
        return page;
    }

    @Override
    public Doorplate update_doorplate_status(Doorplate doorplate) {
        doorplateMapper.update_doorplate_status(doorplate);
        LambdaQueryWrapper<Doorplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Doorplate::getId, doorplate.getId());
        return doorplateMapper.selectOne(wrapper);

    }

    @Override
    public DoorplateVO insert(DoorplateInsertDTO dto) {
        Admin admin = SessionUtils.getCurrentAdminInfo();
        if (admin == null) {
            throw new NotLoginException("请先登录");
        }

        doorplateMapper.insertDoorplate(dto);
        Long doorplateId = dto.getId();

        return doorplateMapper.selectByIdWithClazzStreet(doorplateId);
    }

    @Override
    public Page<DoorplateVO> queryByUser(DoorplateQuery query, PageDTO pageDTO) {
        Page<DoorplateVO> page = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());
        query.setRange(query.getRange() * 1000); // 将范围转换为米
        page = doorplateMapper.queryByUserWithClazzStreet(query, page);
        return page;
    }

    @Override
    public List<DoorplateSummaryVO> summary(DoorplateSummaryQuery query) {
        adminService.auth();
        List<String> groupByFields = getGroupByFields(query.getGroupBy().replaceAll(",\\s+", ","));
        checkList(groupByFields);
        System.out.println("test:" + String.join(",", groupByFields));

        return doorplateMapper.summary(query,
                String.join(",", groupByFields));

    }

    private List<String> getGroupByFields(String groupByRaw) {
        if (!StringUtils.hasText(groupByRaw)) return Collections.emptyList();
        return Arrays.stream(groupByRaw.split(","))
                .map(this::humpToUnderline)
                .toList();
    }

    private String humpToUnderline(String s) {
        return s.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();
    }

    private void checkList(List<String> cols) {
        Set<String> white = Set.of(
                "street_id", "division_id",
                "code_status",  "clazz_id"
        );
        for (String c : cols) {
            if (!white.contains(c)) {
                throw new IllegalArgException("不支持分组/求和字段: " + c);
            }
        }
    }
}
